//
//  SignalRCoordinator.swift
//  gkb_signalr
//
//  Created by Doris on 2022/4/12.
//

import Foundation
import SwiftSignalRClient

protocol SignalRCoordinatorDelegate {
    func onConnectStateChanged(_ state: Bool) -> Void
    func onMessageReceived(_ message: String) -> Void
}

public class SignalRCoordinator: NSObject {
    static let instance = SignalRCoordinator()
    public override func copy() -> Any {
        return self // SignalRCoordinator.instance
    }
    
    public override func mutableCopy() -> Any {
        return self // SignalRCoordinator.instance
    }
    
    private var connection: HubConnection?
    var delegate: SignalRCoordinatorDelegate?
    
    func connectToServer(_ arguments: Any?){
        let args = arguments as! [String: Any?]
        guard let url = args["url"] as? String,let token = args["token"] as? String else{
            return
        }
        connection?.stop()
        //"https://staging-api.geekbuy.cn/ios/hub?sessionId=7c4affec-8612-4928-bec7-b94e4e718dfc&client=IOS"
        connection = HubConnectionBuilder(url: URL(string: url)!)
            .withHttpConnectionOptions(configureHttpOptions: { httpConnectionOptions in
                httpConnectionOptions.accessTokenProvider  = {
                    return token
                }
                //httpConnectionOptions.requestTimeout
            })
            .withHubConnectionDelegate(delegate: self)
            .withLogging(minLogLevel: .error)
            .withAutoReconnect()
            .build()
        connection?.on(method: "ReceiveMessage", callback: { (message: String?) in
            self.delegate?.onMessageReceived(message ?? "{}")
//            do {
//                try self.delegate?.onMessageReceived(message ?? "{}")
//            } catch {
//                print(error)
//            }
        })
        
        connection?.start()
        
    }
    
    //应答消息（告知服务器已收到消息id列表）
    func ackMessage(_ arguments: Any?) {
        let args = arguments as! [String: Any?]
        guard let ids = args["ids"] as? Array<Int> else{
            return
        }
        connection?.send(method: "AckMessage", ids)
    }
    
    func reconnect() {
        connection?.start()
    }
    
    func stop() {
        connection?.stop()
    }
}

extension SignalRCoordinator : HubConnectionDelegate{
    public func connectionDidOpen(hubConnection: HubConnection) {
        delegate?.onConnectStateChanged(true)
    }

    public func connectionDidFailToOpen(error: Error) {
        delegate?.onConnectStateChanged(false)
    }

    public func connectionDidClose(error: Error?) {
        delegate?.onConnectStateChanged(false)
    }

    public func connectionWillReconnect(error: Error) {
        
    }

    public func connectionDidReconnect() {
        delegate?.onConnectStateChanged(true)
    }
}

